package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.OverFlowDao;
import com.atguigu.jxc.dao.UserDao;
import com.atguigu.jxc.entity.OverflowList;
import com.atguigu.jxc.entity.OverflowListGoods;
import com.atguigu.jxc.entity.User;
import com.atguigu.jxc.service.OverFlowService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dyqstart
 * @create 2021-09-04-20:26
 * @since 1.0.0
 */
@Service
public class OverFlowServiceImpl implements OverFlowService {

    @Autowired
    OverFlowDao overFlowDao;

    @Autowired
    UserDao userDao;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOverFlow(OverflowList overflowList, String overflowListGoodsStr) {
        User user = userDao.findUserByName((String) SecurityUtils.getSubject().getPrincipal());
        Integer userId = user.getUserId();
        overflowList.setUserId(userId);
        overFlowDao.saveOverFlowList(overflowList);
        Integer overflowListId = overflowList.getOverflowListId();
        try {
            List<OverflowListGoods> list = new ObjectMapper().readValue(overflowListGoodsStr, new TypeReference<List<OverflowListGoods>>() {
            });
            for (OverflowListGoods overflowListGoods : list) {
                overflowListGoods.setOverflowListId(overflowListId);
                overFlowDao.saveOverFlowListGoods(overflowListGoods);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @Override
    public Map<String, Object> getOverflowListGoods(String sTime, String eTime) {

        List<OverflowList> list = overFlowDao.getOverflowListGoods(sTime,eTime);
        HashMap<String, Object> map = new HashMap<>();
        map.put("rows",list);
        return map;
    }

    @Override
    public Map<String, Object> getOverflowListGoodsByOverflowListId(Integer overflowListId) {
        List<OverflowListGoods> list = overFlowDao.getOverflowListGoodsByOverflowListId(overflowListId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("rows",list);
        return map;
    }
}
